package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLObjectDoing;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.IntegrationChannel;
import com.rockcent.mall.lib.dto.IntegrationChannelDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by DK on 16/12/17.
 */
@Repository
public class IntegrationChannelRepositoryImpl implements IntegrationChannelRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(IntegrationChannelRepositoryImpl.class);


    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;


    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResult<IntegrationChannelDto> findByNameAndMallIdAndIsDelete(String name, Long mallId, Whether whether, PageResult pageResult) {
        SQLPageDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s FROM integration_channel f where mall_id = :mallId");
            params.put("mallId", mallId);
            if (StringUtils.isNotBlank(name)) {
                sql.append(" and `name` like :name");
                params.put("name", "%" + name + "%");
            }
            if (null != whether) {
                sql.append(" and is_delete = :isDelete");
                params.put("isDelete", whether.toString());
            }
            sql.append(" order by f.date_created desc");
            fields.append(" f.id,f.name,f.mall_id ");
        };
        return doing.go(pageResult, IntegrationChannelDto.class, objectMapper, jdbcTemplate, log);
    }

    @Override
    public Long caculateQuantityByChannelId(Long integrationChannelId, Long mallId) {
        SQLObjectDoing<Long> result = (sql, fields, params, typeReferenceMap) -> {
//            sql.append("select %s FROM intergration_cash_wallet f");
            sql.append("select %s from mall_cash_coupon c WHERE  c.is_delete='NO' and c.mall_id =:mallId and c.integration_channel_id=:integrationChannelId ");
            params.put("mallId", mallId);
            params.put("integrationChannelId", integrationChannelId);
            fields.append(" sum(c.quantity) ");
        };
        return result.go(Long.class, jdbcTemplate, log, objectMapper);
    }

}
